#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查MongoDB数据库中的民法典数据
"""

from pymongo import MongoClient
from datetime import datetime

def check_mongodb_data():
    """检查MongoDB数据库中的数据"""
    
    print("=" * 60)
    print("🔍 检查MongoDB数据库中的民法典数据")
    print("=" * 60)
    
    try:
        # 连接MongoDB
        client = MongoClient("mongodb://localhost:27017/")
        
        # 列出所有数据库
        print("\n📂 所有数据库列表:")
        db_list = client.list_database_names()
        for db_name in db_list:
            if 'civil' in db_name.lower() or 'law' in db_name.lower() or db_name == 'civil_code_db':
                print(f"   ✅ {db_name} (目标数据库)")
            else:
                print(f"   - {db_name}")
        
        # 连接到民法典数据库
        db = client['civil_code_db']
        
        print(f"\n🎯 检查数据库: civil_code_db")
        
        # 列出所有集合
        collections = db.list_collection_names()
        print(f"\n📋 集合列表:")
        for collection in collections:
            print(f"   - {collection}")
        
        # 检查民法典条文集合
        if 'civil_code_articles' in collections:
            collection = db['civil_code_articles']
            
            # 统计数据
            total_count = collection.count_documents({})
            print(f"\n📊 civil_code_articles 集合统计:")
            print(f"   - 总条文数: {total_count}")
            
            if total_count > 0:
                # 显示前5条数据
                print(f"\n📄 前5条法条数据:")
                articles = list(collection.find({}).limit(5))
                for i, article in enumerate(articles, 1):
                    print(f"   {i}. {article.get('article_number', 'N/A')}: {article.get('title', article.get('content', 'N/A')[:50])}")
                
                # 按编统计
                print(f"\n📚 按编统计:")
                pipeline = [
                    {"$group": {
                        "_id": "$chapter_info.part",
                        "count": {"$sum": 1}
                    }},
                    {"$sort": {"_id": 1}}
                ]
                
                part_stats = list(collection.aggregate(pipeline))
                for stat in part_stats:
                    part_name = stat['_id'] or "未分类"
                    print(f"   - {part_name}: {stat['count']} 条")
                
                # 检查索引
                print(f"\n🔍 索引信息:")
                indexes = collection.list_indexes()
                for index in indexes:
                    index_name = index.get('name', 'unnamed')
                    index_keys = list(index.get('key', {}).keys())
                    print(f"   - {index_name}: {', '.join(index_keys)}")
                
                # 测试查询
                print(f"\n🧪 测试查询:")
                
                # 1. 按条文号查询
                first_article = collection.find_one({"article_number": "第一条"})
                if first_article:
                    print(f"   ✅ 条文号查询成功: 找到 {first_article['article_number']}")
                    print(f"      内容: {first_article.get('content', 'N/A')[:100]}...")
                else:
                    print(f"   ❌ 条文号查询失败")
                
                # 2. 全文搜索测试
                try:
                    search_results = list(collection.find(
                        {"$text": {"$search": "民事主体"}},
                        {"article_number": 1, "title": 1, "score": {"$meta": "textScore"}}
                    ).sort([("score", {"$meta": "textScore"})]).limit(3))
                    
                    if search_results:
                        print(f"   ✅ 全文搜索成功: 找到 {len(search_results)} 条相关法条")
                        for result in search_results:
                            print(f"      - {result['article_number']}: {result.get('title', 'N/A')[:50]}...")
                    else:
                        print(f"   ⚠️ 全文搜索无结果")
                except Exception as e:
                    print(f"   ❌ 全文搜索失败: {str(e)}")
                
                # 3. 按章节查询
                chapter_results = list(collection.find(
                    {"chapter_info.part": "第一编 总则"},
                    {"article_number": 1, "title": 1}
                ).limit(5))
                
                if chapter_results:
                    print(f"   ✅ 章节查询成功: 第一编总则有法条")
                    for result in chapter_results:
                        print(f"      - {result['article_number']}: {result.get('title', 'N/A')[:50]}...")
                else:
                    print(f"   ❌ 章节查询失败")
                
                # 4. 关键词查询
                keyword_results = list(collection.find(
                    {"keywords": {"$in": ["民事主体", "合法权益"]}},
                    {"article_number": 1, "keywords": 1}
                ).limit(3))
                
                if keyword_results:
                    print(f"   ✅ 关键词查询成功: 找到 {len(keyword_results)} 条相关法条")
                    for result in keyword_results:
                        keywords = result.get('keywords', [])[:5]  # 显示前5个关键词
                        print(f"      - {result['article_number']}: 关键词 {keywords}")
                else:
                    print(f"   ❌ 关键词查询失败")
                
            else:
                print(f"   ❌ 集合为空，没有数据")
                
        else:
            print(f"\n❌ 未找到 civil_code_articles 集合")
        
        # 检查其他相关集合
        other_collections = ['user_favorites', 'search_history']
        for coll_name in other_collections:
            if coll_name in collections:
                coll = db[coll_name]
                count = coll.count_documents({})
                print(f"\n📋 {coll_name} 集合: {count} 条记录")
            else:
                print(f"\n📋 {coll_name} 集合: 未创建")
        
        print(f"\n✅ 数据库检查完成")
        
    except Exception as e:
        print(f"❌ 数据库连接或查询失败: {str(e)}")
        print(f"💡 请确保MongoDB服务已启动")
        
    finally:
        if 'client' in locals():
            client.close()

if __name__ == "__main__":
    check_mongodb_data()
